from rest_framework.response import Response
from rest_framework.views import APIView

from cart.models import Cart
from cart.ser import CartSer, CartListSer
from login.models import User
from utils.authoriaztion import MyAuthentication

# Create your views here.
class AddCart(APIView):
    authentication_classes = [MyAuthentication,]
    def post(self,request):
        user=request.data.get('user',None)
        course=request.data.get('course',None)
        if not user or not course:
            return Response({"msg":"参数不完整"})
        cartinfo=Cart.objects.filter(user=user,course=course).first()
        if cartinfo:
            return Response({"msg":"已购买过"})
        ser=CartSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"msg":"添加成功"})
        else:
            return Response({"msg":ser.errors})
class CartList(APIView):
    authentication_classes = [MyAuthentication,]
    def get(self,request):
        user=request.query_params.get('user')
        if not user:
            return Response({"msg":"参数不完整"})
        cartlist=Cart.objects.filter(user=user)
        ser=CartListSer(cartlist,many=True)
        return Response({"msg":"获取成功","data":ser.data,"code":200})
class DelCart(APIView):
    authentication_classes = [MyAuthentication, ]
    def delete(self,request):
        cart_id=request.query_params.get('cart_id',None)
        user=request.query_params.get('user',None)
        if not cart_id and not user:
            return Response({"msg":"参数不完整"})
        Cart.objects.filter(pk=cart_id,user=user).delete()
        return Response({"msg":"删除成功"})
class ChargeOne(APIView):
    authentication_classes = [MyAuthentication, ]
    def put(self,request):
        cartid=request.data.get('cartid',None)
        if not cartid:
            return Response({"msg":"参数不完整"})
        info=Cart.objects.filter(pk=cartid).first()
        info.is_select=not info.is_select
        info.save()
        return Response({"msg":"修改成功"})
class ChargeAll(APIView):
    authentication_classes = [MyAuthentication, ]
    def put(self,request):
        user=request.data.get('user',None)
        selected=request.data.get('selected',None)
        if not user:
            return Response({"msg":"参数不完整"})
        cartlist=Cart.objects.filter(user=user).update(is_select=selected)
        return Response({"msg":"修改成功"})
